#include "fileinfo.h"

#include <Windows.h>

struct file_info* open_file(char* name)
{
  HANDLE file, mapping;
  void* data;
  struct file_info* finfo;

  file = CreateFileA(name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
    0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if (file == INVALID_HANDLE_VALUE) {
    goto Exit0;
  }
  mapping = CreateFileMappingA(file, 0, PAGE_READONLY, 0, 0, 0);
  if (mapping == 0) {
    goto Exit1;
  }
  data = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
  if (data == 0) {
    goto Exit2;
  }

  finfo = (struct file_info*)malloc(sizeof(*finfo));
  finfo->file = file;
  finfo->mapping = mapping;
  finfo->data = data;
  finfo->size = (int)GetFileSize(file, 0);
  return (finfo);

Exit2:
  CloseHandle(mapping);
Exit1:
  CloseHandle(file);
Exit0:
  return (0);
}

void close_file(struct file_info* handle)
{
  if (handle == 0) {
    return;
  }
  UnmapViewOfFile(handle->data);
  CloseHandle(handle->mapping);
  CloseHandle(handle->file);
  free(handle);
}
